package com.atguigu.gulimall.order.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.gulimall.order.vo.UserInfo1;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfo1> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        // 这个请求直接放行
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match =antPathMatcher.match("/order/order/status/**", uri);
        boolean match1 =antPathMatcher.match("/payed/**", uri);
        boolean match2 =antPathMatcher.match("/order/order/**", uri);
        if(match || match1 ||match2){
            return true;
        }
        // 获取session
        HttpSession session = request.getSession();
        UserInfo1 userInfo1 = new UserInfo1();
        // 获取登录用户
        String username =(String)session.getAttribute(AuthServerConstant.LOGIN_USER);
        Long userId=null;
        if (username!=null){
            userId =Long.valueOf(session.getAttribute(AuthServerConstant.LOGIN_USERId).toString());
        }
        if(username != null){
            userInfo1.setUserName(username);
            userInfo1.setUserId(userId);
            //加上ThreadLocal共享数据，是为了登录后把用户放到本地内存，而不是每次都去远程session里查
            threadLocal.set(userInfo1);
            return true;
        }else{
            // 没登陆就去登录
            session.setAttribute("msg", AuthServerConstant.NOT_LOGIN);
            response.sendRedirect("http://auth.jiajialemall.com/login.html");
            return false;
        }
    }
}

